package org.afi.mushroomplayer;

import java.util.ArrayList;
import java.util.List;

import org.afi.mushroomplayer.components.AllSongsView;
import org.afi.mushroomplayer.components.PlayListView;
import org.afi.mushroomplayer.components.PlayingView;
import org.afi.mushroomplayer.model.SongInfo;
import org.afi.mushroomplayer.utils.DialogToastUtils;
import org.afi.mushroomplayer.utils.MediaScanner;
import org.afi.mushroomplayer.utils.SongUtils;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;

public class MainActivity extends Activity {

    private static final String TAG = "MAIN";
    
    private static final int MSG_SCAN_DONE = 1;
    private static final int MSG_LOADING_DONE = 2;
	private ViewGroup mMainView;
	private ViewPager mViewPager;
	private AllSongsView mAllView;
	private PlayingView mPlayingView;
	private PlayListView mPlayListView;
	private ProgressDialog mProgressDialog;
	
	private MediaScanner mScanner;
	private MyScanThread mScanThread;
	private MyLoadingThread mLoadingThread;
	private OnEventHandleListener mEventHandleListener;
	
	private List<View> mViewList;
	private List<SongInfo> mSongList;
	private ArrayList<String> mUrlList;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
            case MSG_SCAN_DONE:
                mAllView.setSongList(mSongList);
                load();
                break;
            case MSG_LOADING_DONE:
                // TODO mPlayList.setList(blablabla);
                mProgressDialog.dismiss();
                break;
            }
        }

    };
	    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		LayoutInflater inflater = getLayoutInflater();
		mMainView = (ViewGroup)inflater.inflate(R.layout.activity_main, null);
		mViewPager = (ViewPager) mMainView.findViewById(R.id.viewpager);
		mAllView = (AllSongsView) inflater.inflate(R.layout.all_songs, null);
		mPlayingView = (PlayingView) inflater.inflate(R.layout.playing, null);
		mPlayListView = (PlayListView) inflater.inflate(R.layout.play_list, null);
		mViewList = new ArrayList<View>();
		mSongList = new ArrayList<SongInfo>();
		mUrlList = new ArrayList<String>();
		mScanThread = new MyScanThread();
		mLoadingThread = new MyLoadingThread();
		initEventHandleListener();
		
		mViewList.add(mAllView);
		mViewList.add(mPlayingView);
		mViewList.add(mPlayListView);
		mAllView.initView(this);
		mPlayingView.initView(this);
		mPlayListView.initView(this);
		mAllView.setEventHandleListener(mEventHandleListener);
		mPlayingView.setEventHandleListener(mEventHandleListener);
		setContentView(mMainView);
		mViewPager.setAdapter(new MyPagerAdapter(mViewList));
		registerForContextMenu(mAllView.getListView());
		scan();
	}

    private void initEventHandleListener() {
        mEventHandleListener = new OnEventHandleListener() {
            
            @Override
            public void handleEvent(int type, SongInfo info, List<SongInfo> list, int position) {
                switch (type) {
                case EVENT_TYPE_SLIDE_TO_PLAYING_VIEW:
                    handleSlideToPlayingView(list, position);
                    handleEvent(EVENT_TYPE_SET_LIST, info, list, position);
                    break;
                case EVENT_TYPE_SET_LIST:
                    handleSetList(list, position);
                case EVENT_TYPE_PLAY_MUSIC:
                    handlePlayMusic();
                    break;
                case EVENT_TYPE_PAUSE_MUSIC:
                    handlePauseMusic();
                    break;
                case EVENT_TYPE_LAST_SONG:
                    handleLastMusic();
                    break;
                case EVENT_TYPE_NEXT_SONG:
                    handleNextMusic();
                    break;
                case EVENT_TYPE_EXIT_PLAY_SERVICE:
                    handleExitPlayService();
                    break;
                case EVENT_TYPE_LIKE_SONG:
                    handleLikeMusic();
                    break;
                }
            }

            private void handleLikeMusic() {
                Log.i(TAG, "handleLikeMusic");
            }
            
            /**
             * type 6
             */
            private void handleExitPlayService() {
                Intent i = new Intent(getApplicationContext(), PlayService.class);
                stopService(i);
            }

            /**
             * type 5
             */
            private void handleNextMusic() {
                Log.i(TAG, "handleNextMusic");
                Intent i = new Intent(getApplicationContext(), PlayService.class);
                i.putExtra(PlayService.INTENT_TYPE, PlayService.TYPE_NEXT_SONG);
                startService(i);
            }

            /**
             * type 4
             */
            private void handleLastMusic() {
                Log.i(TAG, "handleLastMusic");
                Intent i = new Intent(getApplicationContext(), PlayService.class);
                i.putExtra(PlayService.INTENT_TYPE, PlayService.TYPE_LAST_SONG);
                startService(i);
            }

            /**
             * type 3
             */
            private void handlePauseMusic() {
                Log.i(TAG, "handlePauseMusic");
                Intent i = new Intent(getApplicationContext(), PlayService.class);
                i.putExtra(PlayService.INTENT_TYPE, PlayService.TYPE_PAUSE_MUSIC);
                startService(i);
            }
            
            /**
             * type 2
             */
            private void handlePlayMusic() {
                Log.i(TAG, "handlePlayMusic");
                Intent i = new Intent(getApplicationContext(), PlayService.class);
                i.putExtra(PlayService.INTENT_TYPE, PlayService.TYPE_PLAY_MUSIC);
                startService(i);
            }
            
            /**
             * type 1
             */
            private void handleSetList(List<SongInfo> list, int position) {
                Log.i(TAG, "handleSetList");
                mUrlList.clear();
                for (SongInfo i : list) {
                    mUrlList.add(i.getUrl());
                }
                Intent i = new Intent(getApplicationContext(), PlayService.class);
                i.putExtra(PlayService.INTENT_TYPE, PlayService.TYPE_SET_LIST);
                i.putStringArrayListExtra(PlayService.INTENT_NAME_URL_LIST, mUrlList);
                i.putExtra(PlayService.INTENT_NAME_SONG_INDEX, position);
                startService(i);
            }

            private void handleSlideToPlayingView(List<SongInfo> list, int position) {
                Log.i(TAG, "handleSlideToPlayingView");
                mViewPager.setCurrentItem(1, true); //滑屏
                mPlayingView.setSong(list.get(position)); //设值
            }
        };
    }
	
	@Override
	public void onDestroy() {
	    super.onDestroy();
	    if (mProgressDialog.isShowing()) {
	        mProgressDialog.dismiss();
	    }
	    mScanThread = null;
	    mLoadingThread = null;
	    mEventHandleListener.handleEvent(OnEventHandleListener.EVENT_TYPE_EXIT_PLAY_SERVICE, null, null, -1);
	}
	
	@Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        menu.setHeaderTitle(mSongList.get(info.position).getTitle());
        menu.add(0, 0, 1, R.string.context_menu_add_to_list);
    }
	
	@Override
    public boolean onContextItemSelected(MenuItem item) {
	    if (item.getItemId() == 0) {
	        addSongToList();
	        return true;
	    } else return false;
	}

    private void addSongToList() {
        Log.i(TAG, "add to list");
    }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem menuItem) {
		super.onOptionsItemSelected(menuItem);
		if (menuItem.getItemId() == R.id.menu_exit) {
//			stopService(PlayingActivity.i);
			finish();
			return true;
		}
		return false;
	}
	
	private void scan() {
	    mProgressDialog = DialogToastUtils.showProgressDialog(this, getText(R.string.title_prompt), getText(R.string.body_prompt_scanning), false, false);
	    mScanThread.start();
	}
	
    private void load() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.setMessage(getText(R.string.body_prompt_loading));
        } else {
            mProgressDialog = DialogToastUtils.showProgressDialog(this, getText(R.string.title_prompt), getText(R.string.body_prompt_loading), false, false);
        }
        mLoadingThread.start();
    }
	
	class MyLoadingThread extends Thread {
	    @Override
	    public void run() {
	        mHandler.sendEmptyMessage(MSG_LOADING_DONE);
	    }
	}
	
	class MyScanThread extends Thread {
	    @Override
        public void run() {
            if (mScanner == null) {
                mScanner = new MediaScanner(getApplicationContext(), mSongList);
            }
            mSongList = mScanner.scan();
            mSongList = SongUtils.sort(mSongList, 1);
            mHandler.sendEmptyMessage(MSG_SCAN_DONE);
        }
    }
	    
	class MyPagerAdapter extends PagerAdapter {

		private List<View> mList;
		
		public MyPagerAdapter(List<View> list) {
			this.mList = list;
		}
		
		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}

		@Override
		public int getItemPosition(Object object) {
			return super.getItemPosition(object);
		}

		@Override
		public void destroyItem(View container, int position, Object object) {
			((ViewPager) container).removeView(mList.get(position));
		}

		@Override
		public Object instantiateItem(View container, int position) {
			((ViewPager) container).addView(mList.get(position));
			return mList.get(position);
		}

		@Override
		public void restoreState(Parcelable state, ClassLoader loader) {

		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View v) {

		}

		@Override
		public void finishUpdate(View v) {

		}

		@Override
		public int getCount() {
			return mList.size();
		}

	}

	public interface OnEventHandleListener {
	    /*
	     * 1-5与service有关
	     */
	    public static final int EVENT_TYPE_SLIDE_TO_PLAYING_VIEW = 0;
	    public static final int EVENT_TYPE_SET_LIST = 1;
	    public static final int EVENT_TYPE_PLAY_MUSIC = 2;
	    public static final int EVENT_TYPE_PAUSE_MUSIC = 3;
	    public static final int EVENT_TYPE_LAST_SONG = 4;
	    public static final int EVENT_TYPE_NEXT_SONG = 5;
        public static final int EVENT_TYPE_EXIT_PLAY_SERVICE = 6;
	    public static final int EVENT_TYPE_LIKE_SONG = 7;
	    
	    public void handleEvent(int type, SongInfo info, List<SongInfo> list, int position);
	}
	
}
